#include "queue.h"

void  errif(int result,const char* msg)
{
    if(result)
    {
        printf("Error: %s\n", msg);
        exit(1);
    }
}

Queue* createQueue()
{
    Queue* queue = (Queue*)malloc(sizeof(Queue));
    queue->head = NULL;
    queue->tail = NULL;
    return queue;
}

void destroyQueue(Queue* queue)
{
    QueueNode* node = queue->head;
    while (node != NULL)
    {
        QueueNode* next = node->next;
        free(node);
        node = next;
    }
    free(queue);
}

void Queue_Enqueue(Queue* queue, int data)
{
    QueueNode* node = (QueueNode*)malloc(sizeof(QueueNode));
    errif(!node, "Could not allocate memory!");

    node->data = data;
    node->next = NULL;

    if (queue->head == NULL)
    {
        queue->head = node;
        queue->tail = node;
    }
    else
    {
        queue->tail->next=node;
        queue->tail = node;
    }
}

int Queue_Dequeue(Queue* queue)
{
    errif(!queue->head, "Queue is empty when dequeue!");

    QueueNode* node = queue->head;
    int data = node->data;
    queue->head = node->next;
    free(node);
    return data;
}

int Queue_Size(Queue* queue)
{
    int size=0;
    errif(!queue, "Queue is empty when front!");
    if(queue->head == NULL && queue->tail == NULL)
    {
        return size;
    }

    QueueNode* temp_node = queue->head;
    while(!temp_node)
    {
        size++;
        if(temp_node==queue->tail)
        {
            break;
        }
        temp_node = temp_node->next;
    }

    return size;
}

//end common queue

Dequeue* Dequeue_Create()
{
    Dequeue* dequeue = (Dequeue*)malloc(sizeof(Dequeue));
    errif(!dequeue, "Could not allocate memory!");
    dequeue->head=NULL;
    dequeue->tail=NULL;
    return dequeue;
}

void Dequeue_Destroy(Dequeue *dequeue)
{
    errif(!dequeue, "Dequeue is empty when destroy!");
    DequeueNode* temp_node=NULL;
    while(!dequeue->head)
    {
        temp_node=dequeue->head;
        dequeue->head=dequeue->head->next;
        free(temp_node);
    }
}

void Dequeue_push_front(Dequeue* dequeue, int data)
{
    errif(!dequeue, "Dequeue is empty when push_front!");
    DequeueNode* new_node = (DequeueNode*)malloc(sizeof(DequeueNode));
    errif(!new_node, "Could not allocate memory!");
    new_node->data = data;
    new_node->next = dequeue->head;
    dequeue->head->pre = new_node;

    dequeue->head = new_node;
    if(dequeue->tail == NULL) //think empty queue problem
    {
        dequeue->tail = new_node;
    }
}

